var tipsTimeout = null;
var countDownTimeout = null;
var Jmts = {
    setHeight: function (id, minusHeight) {
        var h = $(window).height();
        $("#" + id).css("overflow-x", "hidden");
        $("#" + id).css("overflow-y", "auto");
        $("#" + id).css("height", h - minusHeight)
    },
    getTop: function () {
        return window.top
    },
    showMsg: function (details, title) {
        $("#msgContent").empty();
        var detailMsg = '<div id="modelBackground"></div><div id="detailMsg"><h3>' + title + '</h3><div id="msgContent">' + details + '</div><div class="btnBottom"><button id=“closeMsg” class="button">我知道了</button></div></div>';
        Jmts.getTop().$("body").prepend(detailMsg);
        Jmts.getTop().$("body").on("click", ".button", function () {
            Jmts.getTop().$("#modelBackground").remove();
            Jmts.getTop().$("#detailMsg").remove()
        })
    },
    refreashTime: function (delayTime) {
        Jmts.getTop().$("#tipsFrom").off();
        var numText = delayTime / 1000;
        var s = numText - 1;
        clearInterval(countDownTimeout);
        Jmts.getTop().$("#tipsTimeOutShow").text(numText);
        countDownTimeout = setInterval(function () {
            s > -1 ? Jmts.getTop().$("#tipsTimeOutShow").text(s--) : clearInterval(countDownTimeout)
        }, 1000);
        Jmts.getTop().$("body").on("mouseover mouseout", "#tipsFrom", function (event) {
            if (event.type == "mouseover") {
                clearInterval(countDownTimeout);
                Jmts.getTop().$("#tipsTimeOutShow").text(numText)
            } else {
                clearInterval(countDownTimeout);
                Jmts.getTop().$("#tipsTimeOutShow").text(numText);
                s = numText - 1;
                countDownTimeout = setInterval(function () {
                    s > -1 ? Jmts.getTop().$("#tipsTimeOutShow").text(s--) : clearInterval(countDownTimeout)
                }, 1000)
            }
        })
    },
    clearTips: function (delayTime) {
        if (typeof (delayTime) == "undefined") {
            setTimeout(Jmts.removeTips, delayTime)
        } else {
            tipsTimeout = setTimeout(Jmts.removeTips, delayTime);
            clearTimeout(tipsTimeout)
        }
    },
    removeTips: function () {
        var tipsContent = $("#tipsContent");
        var tips = $("#tipsFrom");
        if (tips.length > 0) {
            $("div").remove("#tipsFrom")
        }
        if (tipsContent.length > 0) {
            var bf = $(".tipsfrom");
            bf.remove()
        } else {
            var tf = Jmts.getTop().$(".tipsfrom");
            tf.remove()
        }
    },
    showTips: function (action, msg, details, delayTime) {
        if ($.trim(msg) == "") {
            Jmts.removeTips();
            return
        }
        var tipsContent = $("#tipsContent");
        var closetext = "<span style='margin-left:20px;color:#333;cursor:pointer;font-size:12px;' onclick='Jmts.removeTips();'>【关闭】</span>";
        var msgDetails = Jmts.getTop().$(".msg_details");
        var msgDetailsLocal = $(".msg_details");
        var detailsSpan = "<span class='msg_details'>[详细]</span>";
        Jmts.refreashTime(delayTime);
        if (Jmts.getTop().$(".tipsfrom").length > 0) {
            clearTimeout(tipsTimeout);
            Jmts.removeTips()
        }
        if ($(".tipsfrom").length > 0) {
            Jmts.removeTips()
        }
        if (action == "i") {
            var infotips = "<div class='tipsfrom' id='tipsFrom'><span class='infotips'>" + msg + "</span></div>";
            if (tipsContent.length > 0) {
                $("#tipsContent").prepend(infotips);
                if (details) {
                    $(".infotips").append(detailsSpan)
                }
                $(".infotips").css("visibility", "visible")
            } else {
                Jmts.getTop().$("body").prepend(infotips);
                if (details) {
                    Jmts.getTop().$(".infotips").append(detailsSpan)
                }
                Jmts.getTop().$(".infotips").css("visibility", "visible")
            }
        }
        if (action == "w") {
            clearTimeout(tipsTimeout);
            var warntips = "<div class='tipsfrom' id='tipsFrom'><span class='warntips'>" + msg + " " + "<span style='color:#666;font-size:12px;font-weight:normal;'><span id='tipsTimeOutShow'>" + delayTime / 1000 + "</span>秒后关闭</span>" + "</span></div>";
            $("#tipsContent").empty();
            $("#tipsFrom").remove();
            if (tipsContent.length > 0) {
                $("#tipsContent").prepend(warntips);
                if (details) {
                    $(".warntips").append(detailsSpan)
                }
                $(".warntips").css("visibility", "visible");
                $("body  #tipsfrom").append(closetext)
            } else {
                Jmts.getTop().$("body").prepend(warntips);
                if (details) {
                    Jmts.getTop().$(".warntips").append(detailsSpan)
                }
                Jmts.getTop().$(".warntips").css("visibility", "visible");
                Jmts.getTop().$("body  .warntips").append(closetext)
            }
        }
        if (action == "e") {
            clearTimeout(tipsTimeout);
            var errortips = "<div class='tipsfrom' id='tipsFrom'><span class='errortips'>" + msg + " " + "<span style='color:#666;font-size:12px;font-weight:normal;'><span id='tipsTimeOutShow'>" + delayTime / 1000 + "</span></span>" + "</span></div>";
            $("#tipsContent").empty();
            $("#tipsFrom").remove();
            if (tipsContent.length > 0) {
                $("#tipsContent").prepend(errortips);
                if (details) {
                    $(".errortips").append(detailsSpan)
                }
                $(".errortips").css("visibility", "visible");
                $("body .errortips").append(closetext)
            } else {
                Jmts.getTop().$("body").prepend(errortips);
                if (details) {
                    Jmts.getTop().$(".errortips").append(detailsSpan)
                }
                Jmts.getTop().$(".errortips").css("visibility", "visible");
                Jmts.getTop().$("body .errortips").append(closetext)
            }
        }
        if (delayTime == 0) {
            return
        }
        tipsTimeout = setTimeout(Jmts.removeTips, delayTime);
        Jmts.getTop().$("#tipsFrom").on("mouseover mouseout", "span", function (event) {
            clearTimeout(tipsTimeout);
            if (event.type == "mouseover") {
                clearTimeout(tipsTimeout)
            } else {
                tipsTimeout = setTimeout(Jmts.removeTips, delayTime)
            }
        });
        if (delayTime <= 0) {
            Jmts.getTop().$("body > .tipsfrom > span").append(closetext)
        }
        msgDetails.on("click", function () {
            Jmts.showMsg(details, "详细信息")
        });
        msgDetailsLocal.on("click", function () {
            Jmts.showMsg(details, "详细信息")
        });
        Jmts.getTop().$("#tipsFrom").on("click", ".msg_details", function () {
            Jmts.showMsg(details, "详细信息")
        })
    },
    infoTips: function (msg, details, delayTime) {
        if (!delayTime && delayTime != 0) {
            delayTime = 4000
        }
        Jmts.showTips("i", msg, details, delayTime)
    },
    infoTipsKeep: function (msg) {
        Jmts.showTips("i", msg, "", 0)
    },
    warnTips: function (msg, details, delayTime) {
        if (!delayTime && delayTime != 0) {
            delayTime = delayTime
        }
        Jmts.showTips("w", msg, details, delayTime)
    }, errorTips: function (msg, details, delayTime) {
        if (!delayTime && delayTime != 0) {
            delayTime = delayTime
        }
        Jmts.showTips("e", msg, details, delayTime)
    }, submitForm: function (o, options) {
        if ($(o).valid()) {
            o.ajaxSubmit(options)
        }
    }, ajaxPost: function (url, data, onSuccess, onCompleted) {
        $.ajax({
            url: url, type: "POST", dataType: "json", data: data, beforeSend: function (xhr) {
                showloading()
            }, success: function (result) {
                closeloading();
                if (result.isError) {
                    Jmts.errTips(result.msg);
                    return
                }
                if (result.success) {
                    if (onSuccess) {
                        onSuccess(result)
                    }
                } else {
                    Jmts.warnTips(result.msg, 5)
                }
            }, complete: function (xhr, textStatus) {
                closeloading();
                if (onCompleted) {
                    onCompleted()
                }
            }, error: function (xhr, textStatus, errorThrown) {
                closeloading();
                Jmts.errTips("请求发生了异常。\n" + xhr.responseText, 3)
            }
        })
    }, ajaxSubmit: function (o, onSuccess, onCompleted, onOtherValid) {
        if ($(o).valid()) {
            if (onOtherValid) {
                if (!onOtherValid()) {
                    return false
                }
            }
            $.ajax({
                url: o.action,
                type: o.method,
                dataType: "json",
                data: $(o).serialize(),
                beforeSend: function (xhr) {
                    showloading()
                },
                success: function (result) {
                    closeloading();
                    if (result.isError) {
                        Jmts.errTips(result.msg, 3);
                        return
                    }
                    if (result.success) {
                        if (onSuccess) {
                            onSuccess(result)
                        }
                    } else {
                        Jmts.revertAmtAndRate();
                        Jmts.warnTips(result.msg, 3)
                    }
                },
                complete: function (xhr, textStatus) {
                    closeloading();
                    if (onCompleted) {
                        onCompleted()
                    }
                },
                error: function (xhr, textStatus, errorThrown) {
                    Jmts.revertAmtAndRate();
                    Jmts.errTips("请求发生了异常。\n" + xhr.responseText, 3)
                }
            })
        } else {
            Jmts.tips("页面信息填写不完整。", 2, "alert.gif")
        }
    }, deleteItem: function (msg, url, data, onSuccess) {
        Jmts.confirm(msg, function () {
            Jmts.ajaxPost(url, data, function (result) {
                if (onSuccess) {
                    onSuccess(result)
                }
            })
        })
    }, openDialog: function (pId, pUrl, pTitle, pHeight, pWidth, zIndex) {
        var height = parseInt((window.screen.availHeight - 50) * 0.82);
        var width = parseInt((window.screen.availWidth - 10) * 0.85);
        if (pHeight == null || pHeight == 0 || pHeight == "") {
            pHeight = height
        }
        if (pWidth == null || pWidth == 0 || pWidth == "") {
            pWidth = width
        }
        if (zIndex == null || zIndex == "") {
            zIndex = 10
        }
        var d = $.dialog({
            id: pId,
            title: pTitle,
            height: pHeight,
            width: pWidth,
            padding: 0,
            zIndex: zIndex,
            content: "url:" + pUrl,
            lock: false
        });
        return d
    }, openDialogFun: function (pId, pUrl, pTitle, pHeight, pWidth, zIndex, fn) {
        var d = $.dialog({
            id: pId,
            title: pTitle,
            height: pHeight,
            width: pWidth,
            padding: 0,
            zIndex: zIndex,
            content: "url:" + pUrl,
            close: function () {
                if (typeof fn == "function") {
                    fn()
                }
            },
            lock: true
        });
        return d
    }, openNoticeDialog: function (options) {
        var opts = options || {}, api, aConfig, hide, wrap, top, duration = opts.duration || 800;
        var config = {
            id: "Notice",
            left: "100%",
            top: "100%",
            fixed: true,
            drag: false,
            resize: false,
            init: function (here) {
                api = this;
                aConfig = api.config;
                wrap = api.DOM.wrap;
                top = parseInt(wrap[0].style.top);
                hide = top + wrap[0].offsetHeight;
                wrap.css("top", hide + "px").animate({top: top + "px"}, duration, function () {
                    opts.init && opts.init.call(api, here)
                })
            },
            close: function (here) {
                wrap.animate({top: hide + "px"}, duration, function () {
                    opts.close && opts.close.call(this, here);
                    aConfig.close = $.noop;
                    api.close()
                });
                return false
            }
        };
        for (var i in opts) {
            if (config[i] === undefined) {
                config[i] = opts[i]
            }
        }
        return $.dialog(config)
    }, alert: function (content, callback) {
        $.dialog.alert(content, callback)
    }, confirm: function (content, yes, no) {
        $.dialog.confirm(content, yes, no)
    }, prompt: function (content, yes, value) {
        $.dialog.prompt(content, yes, value)
    }, tips: function (content, time, icon, callback) {
        if (time == null) {
            time = 2
        }
        if (icon == null || icon == "") {
            icon = "tips.gif"
        }
        $.dialog.tips(content, time, icon, callback)
    }, errTips: function (content, time, callback) {
        Jmts.tips(content, time, "error.gif", callback)
    }, succTips: function (content, time, callback) {
        Jmts.tips(content, time, "success.gif", callback)
    }, loadingTips: function (content, time, callback) {
        Jmts.tips(content, time, "loading.gif", callback)
    }, warnTips: function (content, time, callback) {
        Jmts.tips(content, time, "alert.gif", callback)
    }, setFormReadOnly: function () {
        $("input").attr("readonly", "true");
        $("select").attr("disabled", "true");
        $("checkbox").attr("disabled", "true");
        $("radio").attr("disabled", "true");
        $("textarea").attr("readonly", "true");
        $(".Wdate").attr("onfocus", "");
        $(".btn").attr("readonly", "true")
    }, setFormUnReadOnly: function () {
        $("input").attr("readonly", "false");
        $("select").attr("disabled", "false");
        $("textarea").attr("readonly", "false");
        $("checkbox").attr("disabled", "false");
        $("radio").attr("disabled", "false");
        $(".Wdate").attr("onfocus", "WdatePicker()");
        $(".btn").attr("readonly", "false")
    }, formateDate: function (val, formate) {
        if (formate == null || formate == "") {
            formate = "Y-m-d"
        }
        var re = /^[0-9]*[1-9][0-9]*$/;
        if (val) {
            var time = null;
            if (re.test(val)) {
                time = new Date(val)
            } else {
                time = new Date(val)
            }
            return time.dateFormat(formate)
        } else {
            return ""
        }
    }, formatAmt: function (s, n) {
        n = n > 0 && n <= 20 ? n : 2;
        s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
        var l = s.split(".")[0].split("").reverse(), r = s.split(".")[1];
        t = "";
        for (i = 0; i < l.length; i++) {
            t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "")
        }
        return t.split("").reverse().join("") + "." + r
    }, initRate: function (value) {
        if (value == null || value == "" || value.indexOf("%") > -1) {
            return value
        }
        return value + "%"
    }, formatRate: function (value) {
        if (value == null || value == "" || value.indexOf("%") > -1 || value == undefined) {
            return value
        }
        var str = new BigDecimal(value + "").multiply(new BigDecimal("100")) + "";
        var strs = new Array();
        strs = str.split(".");
        if (strs.length > 1) {
            var decimal = strs[1];
            if (decimal.length > 4) {
                decimal = decimal.substring(0, 4)
            }
            str = strs[0] + "." + decimal + "%"
        } else {
            str = strs[0] + "%"
        }
        return str
    }, getAmtValue: function (value) {
        if (value == null || value == "") {
            return ""
        }
        return value.replace(/\,/g, "")
    }, getRateValue: function (value) {
        if (value == null || value == "") {
            return ""
        }
        if (value.indexOf("%") > -1) {
            return new BigDecimal(value.replace("%", "")).multiply(new BigDecimal("0.01"))
        } else {
            return value
        }
    }, getRateInputValue: function (value) {
        if (value == null || value == "") {
            return ""
        }
        if (value.indexOf("%") > -1) {
            return new BigDecimal(value.replace("%", "")).multiply(new BigDecimal("0.01"))
        } else {
            return new BigDecimal(value + "").multiply(new BigDecimal("0.01"))
        }
    }, convertAmtAndRate: function () {
        var allNodes = document.getElementsByTagName("input");
        var node;
        var id;
        var value = "";
        for (var i = 0; i < allNodes.length; i++) {
            node = allNodes[i];
            id = node.getAttribute("id");
            if (node.hasAttribute("isCurrency")) {
                value = $("#" + id).val();
                if (value == null || value == "") {
                    continue
                }
                document.getElementById(id).value = value.replace(/\,/g, "")
            } else {
                if (node.hasAttribute("isRate")) {
                    value = $("#" + id).val();
                    if (value == null || value == "") {
                        continue
                    }
                    if (value.indexOf("%") > -1) {
                        document.getElementById(id).value = new BigDecimal(value.replace("%", "")).multiply(new BigDecimal("0.01"))
                    } else {
                        continue
                    }
                }
            }
        }
    }, revertAmtAndRate: function () {
        var allNodes = document.getElementsByTagName("input");
        var node;
        var id;
        var value = "";
        for (var i = 0; i < allNodes.length; i++) {
            node = allNodes[i];
            id = node.getAttribute("id");
            if (node.hasAttribute("isCurrency")) {
                value = $("#" + id).val();
                if (value == null || value == "") {
                    continue
                }
                document.getElementById(id).value = Jmts.formatAmt(value + "")
            } else {
                if (node.hasAttribute("isRate")) {
                    value = $("#" + id).val();
                    if (value == null || value == "") {
                        continue
                    }
                    document.getElementById(id).value = Jmts.formatRate(value + "")
                }
            }
        }
    }, loadProvince: function (url, provinceId, province, city, area, provinceValue) {
        $("#" + province).html("");
        $("#" + province).append("<option value=''>请选择省份</option>");
        var data = {countryCode: provinceId};
        Jmts.ajaxPost(url, data, function (result) {
            if (result.success) {
                var provinceList = result.resultData.systemProvinceList;
                var provinces = eval(provinceList);
                for (var i in provinces) {
                    if (provinces[i].id == provinceValue) {
                        $("#" + province).append("<option value='" + provinces[i].id + "' selected='selected'>" + provinces[i].provinceName + "</option>")
                    } else {
                        $("#" + province).append("<option value='" + provinces[i].id + "'>" + provinces[i].provinceName + "</option>")
                    }
                }
            } else {
                Jmts.warnTips(result.msg)
            }
        });
        if (provinceValue == null || provinceValue == "" || provinceValue == "undefined") {
            $("#" + city).html("");
            $("#" + city).append("<option value=''>请选择城市</option>");
            $("#" + area).html("");
            $("#" + area).append("<option value=''>请选择区域</option>")
        }
    }, loadCity: function (url, provinceId, province, city, area, cityValue) {
        $("#" + city).html("");
        $("#" + city).append("<option value=''>请选择城市</option>");
        var data = {provinceId: provinceId};
        Jmts.ajaxPost(url, data, function (result) {
            if (result.success) {
                var cityList = result.systemCityList;
                var citys = eval(cityList);
                for (var i in citys) {
                    if (cityValue != null && cityValue != "" && cityValue != "undefined") {
                        $("#" + city).append("<option value='" + citys[i].id + "' selected='selected'>" + citys[i].cityName + "</option>")
                    } else {
                        $("#" + city).append("<option value='" + citys[i].id + "'>" + citys[i].cityName + "</option>")
                    }
                }
            } else {
                Jmts.warnTips(result.msg)
            }
        });
        if ($("#" + province).val() == "") {
            $("#" + city).html("");
            $("#" + city).append("<option value=''>请选择城市</option>");
            $("#" + area).html("");
            $("#" + area).append("<option value=''>请选择区域</option>")
        }
        if ($("#" + city).val() == "") {
            $("#" + area).html("");
            $("#" + area).append("<option value=''>请选择区域</option>")
        }
    }, loadArea: function (url, cityId, area, areaValue) {
        $("#" + area).html("");
        $("#" + area).append("<option value=''>请选择区域</option>");
        var data = {cityId: cityId};
        Jmts.ajaxPost(url, data, function (result) {
            if (result.success) {
                var areaList = result.resultData.systemAreaList;
                var areas = eval(areaList);
                for (var i in areas) {
                    if (areaValue != null && areaValue != "" && areaValue != "undefined") {
                        $("#" + area).append("<option value='" + areas[i].id + "' selected='selected'>" + areas[i].areaName + "</option>")
                    } else {
                        $("#" + area).append("<option value='" + areas[i].id + "'>" + areas[i].areaName + "</option>")
                    }
                }
            } else {
                Jmts.warnTips(result.msg)
            }
        })
    }, getParams: function (key) {
        var href = window.document.location.href;
        if (href.indexOf("?") != -1) {
            var paramStr = href.substring(href.indexOf("?") + 1, href.length);
            if (paramStr.indexOf(key + "=") != -1) {
                paramStr = paramStr.substring(paramStr.indexOf(key + "="), paramStr.length);
                if (paramStr.indexOf("&") != -1) {
                    return paramStr.substring(paramStr.indexOf("=") + 1, paramStr.indexOf("&"))
                } else {
                    return paramStr.substring(paramStr.indexOf("=") + 1, paramStr.length)
                }
            } else {
                return ""
            }
        }
    }, isEmpty: function (data) {
        if (data == null || data == "" || data == undefined || data == "undefined") {
            return true
        }
        return false
    }, convertSelectState: function (selectIds) {
        if (selectIds == null || selectIds == "" || selectIds == undefined || selectIds == "undefined") {
            return false
        }
        for (var i = 0; i < selectIds.length; i++) {
            $("#" + selectIds[i]).attr("disabled", false)
        }
    }, revertSelectState: function (selectIds) {
        if (selectIds == null || selectIds == "" || selectIds == undefined || selectIds == "undefined") {
            return false
        }
        for (var i = 0; i < selectIds.length; i++) {
            $("#" + selectIds[i]).attr("disabled", true)
        }
    }
};
